/*!
 * \file test_hft_stra_base_ctx_comprehensive.cpp
 * \project WonderTrader
 *
 * \author Assistant
 * \date 2024/12/19
 * 
 * \brief HFT策略基础上下文综合测试文件
 * 
 * \details 本文件包含对HftStraBaseCtx类的全面测试，涵盖：
 *          - HFT策略生命周期管理
 *          - 高频交易操作（买卖、开平仓、撤单）
 *          - Level2数据处理（委托队列、委托明细、成交明细）
 *          - 订单管理（FAK/FOK订单、订单状态跟踪）
 *          - 持仓管理（实时持仓、盈亏计算）
 *          - 数据订阅（高频数据订阅）
 *          - 异常处理和边界条件
 *          - 性能测试和并发安全
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <memory>
#include <thread>
#include <chrono>
#include <atomic>
#include <vector>
#include <string>
#include <map>

// 包含被测试的头文件
#include "../../src/WtCore/HftStraBaseCtx.h"
#include "../../src/WtCore/WtHftEngine.h"
#include "../../src/WtCore/TraderAdapter.h"
#include "../../src/Includes/WTSContractInfo.hpp"
#include "../../src/Includes/WTSDataDef.hpp"

using namespace testing;
using namespace wtp;

/**
 * @class MockWtHftEngine
 * @brief 模拟HFT引擎类
 */
class MockWtHftEngine : public WtHftEngine {
public:
    MockWtHftEngine() = default;
    virtual ~MockWtHftEngine() = default;
    
    MOCK_METHOD(uint32_t, get_trading_date, (), (override));
    MOCK_METHOD(uint32_t, get_date, (), (override));
    MOCK_METHOD(uint32_t, get_min_time, (), (override));
    MOCK_METHOD(uint32_t, get_secs, (), (override));
    MOCK_METHOD(WTSCommodityInfo*, get_commodity_info, (const char* stdCode), (override));
    MOCK_METHOD(WTSKlineSlice*, get_kline_slice, (uint32_t cid, const char* stdCode, const char* period, uint32_t count, uint32_t times), (override));
    MOCK_METHOD(WTSTickSlice*, get_tick_slice, (uint32_t cid, const char* stdCode, uint32_t count), (override));
    MOCK_METHOD(WTSTickData*, get_last_tick, (uint32_t cid, const char* stdCode), (override));
    MOCK_METHOD(double, get_cur_price, (const char* stdCode), (override));
    MOCK_METHOD(void, sub_tick, (uint32_t cid, const char* stdCode), (override));
    MOCK_METHOD(double, stra_get_fund_data, (uint32_t cid, int flag), (override));
};

/**
 * @class MockTraderAdapter
 * @brief 模拟交易适配器类
 */
class MockTraderAdapter : public TraderAdapter {
public:
    MockTraderAdapter() : TraderAdapter(nullptr, nullptr) {}
    
    MOCK_METHOD(uint32_t, buy, (const char* stdCode, double price, double qty, int flag), (override));
    MOCK_METHOD(uint32_t, sell, (const char* stdCode, double price, double qty, int flag), (override));
    MOCK_METHOD(uint32_t, openLong, (const char* stdCode, double price, double qty, int flag), (override));
    MOCK_METHOD(uint32_t, openShort, (const char* stdCode, double price, double qty, int flag), (override));
    MOCK_METHOD(uint32_t, closeLong, (const char* stdCode, double price, double qty, bool isToday, int flag), (override));
    MOCK_METHOD(uint32_t, closeShort, (const char* stdCode, double price, double qty, bool isToday, int flag), (override));
    MOCK_METHOD(bool, cancel, (uint32_t localid), (override));
    MOCK_METHOD(double, getPosition, (const char* stdCode, bool bValidOnly), (override));
    MOCK_METHOD(bool, isConnected, (), (override));
    MOCK_METHOD(const char*, id, (), (const, override));
};

/**
 * @class HftStraBaseCtxComprehensiveTest
 * @brief HFT策略基础上下文综合测试类
 */
class HftStraBaseCtxComprehensiveTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 创建模拟对象
        mock_engine_ = std::make_shared<MockWtHftEngine>();
        mock_trader_ = std::make_shared<MockTraderAdapter>();
        
        // 创建被测试对象
        ctx_ = std::make_unique<HftStraBaseCtx>(mock_engine_.get(), "test_hft_strategy", true);
        
        // 设置交易适配器
        ctx_->setTrader(mock_trader_.get());
        
        // 初始化测试数据
        initTestData();
        
        // 设置默认期望
        setupDefaultExpectations();
    }
    
    void TearDown() override {
        ctx_.reset();
        mock_trader_.reset();
        mock_engine_.reset();
    }
    
    /**
     * @brief 初始化测试数据
     */
    void initTestData() {
        // 创建测试合约信息
        test_contract_ = WTSContractInfo::create("SHFE.rb2501", "rb2501", "SHFE", "rb", "螺纹钢", "SHFE", 10);
        
        // 创建测试Tick数据
        test_tick_ = WTSTickData::create("SHFE.rb2501");
        test_tick_->set_price(4000.0);
        test_tick_->set_volume(1000);
        test_tick_->set_turnover(4000000.0);
        test_tick_->set_open_interest(50000);
        test_tick_->set_trading_date(20241219);
        test_tick_->set_action_date(20241219);
        test_tick_->set_action_time(93000000);
    }
    
    /**
     * @brief 设置默认期望
     */
    void setupDefaultExpectations() {
        // 设置引擎默认行为
        ON_CALL(*mock_engine_, get_trading_date())
            .WillByDefault(Return(20241219));
        
        ON_CALL(*mock_engine_, get_date())
            .WillByDefault(Return(20241219));
        
        ON_CALL(*mock_engine_, get_min_time())
            .WillByDefault(Return(93000));
        
        ON_CALL(*mock_engine_, get_secs())
            .WillByDefault(Return(0));
        
        ON_CALL(*mock_engine_, get_commodity_info(_))
            .WillByDefault(Return(test_contract_));
        
        ON_CALL(*mock_engine_, get_last_tick(_, _))
            .WillByDefault(Return(test_tick_));
        
        ON_CALL(*mock_engine_, get_cur_price(_))
            .WillByDefault(Return(4000.0));
        
        ON_CALL(*mock_engine_, stra_get_fund_data(_, _))
            .WillByDefault(Return(1000000.0));
        
        // 设置交易适配器默认行为
        ON_CALL(*mock_trader_, isConnected())
            .WillByDefault(Return(true));
        
        ON_CALL(*mock_trader_, id())
            .WillByDefault(Return("test_trader"));
        
        ON_CALL(*mock_trader_, getPosition(_, _))
            .WillByDefault(Return(0.0));
        
        ON_CALL(*mock_trader_, buy(_, _, _, _))
            .WillByDefault(Return(60001));
        
        ON_CALL(*mock_trader_, sell(_, _, _, _))
            .WillByDefault(Return(60002));
        
        ON_CALL(*mock_trader_, openLong(_, _, _, _))
            .WillByDefault(Return(60003));
        
        ON_CALL(*mock_trader_, openShort(_, _, _, _))
            .WillByDefault(Return(60004));
        
        ON_CALL(*mock_trader_, closeLong(_, _, _, _, _))
            .WillByDefault(Return(60005));
        
        ON_CALL(*mock_trader_, closeShort(_, _, _, _, _))
            .WillByDefault(Return(60006));
        
        ON_CALL(*mock_trader_, cancel(_))
            .WillByDefault(Return(true));
    }

protected:
    std::shared_ptr<MockWtHftEngine> mock_engine_;
    std::shared_ptr<MockTraderAdapter> mock_trader_;
    std::unique_ptr<HftStraBaseCtx> ctx_;
    
    WTSContractInfo* test_contract_;
    WTSTickData* test_tick_;
};

/**
 * @brief 测试HFT策略基本功能
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestBasicFunctionality) {
    // 测试策略ID获取
    uint32_t ctx_id = ctx_->id();
    EXPECT_GT(ctx_id, 6000); // HFT策略ID从6000开始
    EXPECT_LT(ctx_id, 10000);
    
    // 测试策略名称
    EXPECT_STREQ(ctx_->name(), "test_hft_strategy");
    
    // 测试初始状态
    EXPECT_EQ(ctx_->stra_get_position("SHFE.rb2501"), 0.0);
    EXPECT_GT(ctx_->stra_get_fund_data(0), 0.0);
    
    std::cout << "HFT策略基本功能测试通过，策略ID: " << ctx_id << std::endl;
}

/**
 * @brief 测试HFT策略初始化
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestStrategyInitialization) {
    // 执行初始化
    EXPECT_NO_THROW(ctx_->on_init());
    
    // 验证初始化后的状态
    uint32_t trading_date = ctx_->stra_get_tdate();
    uint32_t date = ctx_->stra_get_date();
    uint32_t time = ctx_->stra_get_time();
    uint32_t secs = ctx_->stra_get_secs();
    
    EXPECT_EQ(trading_date, 20241219);
    EXPECT_EQ(date, 20241219);
    EXPECT_EQ(time, 93000);
    EXPECT_EQ(secs, 0);
    
    std::cout << "HFT策略初始化测试通过" << std::endl;
}

/**
 * @brief 测试高频买入操作
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestHighFrequencyBuy) {
    const char* stdCode = "SHFE.rb2501";
    double price = 4000.0;
    double qty = 10.0;
    const char* userTag = "hft_buy";
    
    // 期望交易适配器接收高频买入订单
    EXPECT_CALL(*mock_trader_, buy(stdCode, price, qty, 0))
        .Times(1)
        .WillOnce(Return(60001));
    
    // 执行高频买入操作
    OrderIDs order_ids = ctx_->stra_buy(stdCode, price, qty, userTag);
    
    // 验证订单ID
    EXPECT_GT(order_ids.size(), 0);
    if (order_ids.size() > 0) {
        EXPECT_EQ(order_ids[0], 60001);
    }
    
    std::cout << "高频买入操作测试通过" << std::endl;
}

/**
 * @brief 测试高频卖出操作
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestHighFrequencySell) {
    const char* stdCode = "SHFE.rb2501";
    double price = 4000.0;
    double qty = 10.0;
    const char* userTag = "hft_sell";
    
    // 期望交易适配器接收高频卖出订单
    EXPECT_CALL(*mock_trader_, sell(stdCode, price, qty, 0))
        .Times(1)
        .WillOnce(Return(60002));
    
    // 执行高频卖出操作
    OrderIDs order_ids = ctx_->stra_sell(stdCode, price, qty, userTag);
    
    // 验证订单ID
    EXPECT_GT(order_ids.size(), 0);
    if (order_ids.size() > 0) {
        EXPECT_EQ(order_ids[0], 60002);
    }
    
    std::cout << "高频卖出操作测试通过" << std::endl;
}

/**
 * @brief 测试开多仓操作
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestEnterLongOperation) {
    const char* stdCode = "SHFE.rb2501";
    double price = 4000.0;
    double qty = 10.0;
    const char* userTag = "hft_long";
    
    // 期望交易适配器接收开多仓订单
    EXPECT_CALL(*mock_trader_, openLong(stdCode, price, qty, 0))
        .Times(1)
        .WillOnce(Return(60003));
    
    // 执行开多仓操作
    uint32_t order_id = ctx_->stra_enter_long(stdCode, price, qty, userTag);
    
    // 验证订单ID
    EXPECT_EQ(order_id, 60003);
    
    std::cout << "开多仓操作测试通过" << std::endl;
}

/**
 * @brief 测试开空仓操作
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestEnterShortOperation) {
    const char* stdCode = "SHFE.rb2501";
    double price = 4000.0;
    double qty = 10.0;
    const char* userTag = "hft_short";
    
    // 期望交易适配器接收开空仓订单
    EXPECT_CALL(*mock_trader_, openShort(stdCode, price, qty, 0))
        .Times(1)
        .WillOnce(Return(60004));
    
    // 执行开空仓操作
    uint32_t order_id = ctx_->stra_enter_short(stdCode, price, qty, userTag);
    
    // 验证订单ID
    EXPECT_EQ(order_id, 60004);
    
    std::cout << "开空仓操作测试通过" << std::endl;
}

/**
 * @brief 测试平多仓操作
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestExitLongOperation) {
    const char* stdCode = "SHFE.rb2501";
    double price = 4010.0;
    double qty = 10.0;
    const char* userTag = "hft_exit_long";
    bool isToday = false;
    
    // 期望交易适配器接收平多仓订单
    EXPECT_CALL(*mock_trader_, closeLong(stdCode, price, qty, isToday, 0))
        .Times(1)
        .WillOnce(Return(60005));
    
    // 执行平多仓操作
    uint32_t order_id = ctx_->stra_exit_long(stdCode, price, qty, userTag, isToday);
    
    // 验证订单ID
    EXPECT_EQ(order_id, 60005);
    
    std::cout << "平多仓操作测试通过" << std::endl;
}

/**
 * @brief 测试平空仓操作
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestExitShortOperation) {
    const char* stdCode = "SHFE.rb2501";
    double price = 3990.0;
    double qty = 10.0;
    const char* userTag = "hft_exit_short";
    bool isToday = false;
    
    // 期望交易适配器接收平空仓订单
    EXPECT_CALL(*mock_trader_, closeShort(stdCode, price, qty, isToday, 0))
        .Times(1)
        .WillOnce(Return(60006));
    
    // 执行平空仓操作
    uint32_t order_id = ctx_->stra_exit_short(stdCode, price, qty, userTag, isToday);
    
    // 验证订单ID
    EXPECT_EQ(order_id, 60006);
    
    std::cout << "平空仓操作测试通过" << std::endl;
}

/**
 * @brief 测试撤单功能
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestOrderCancellation) {
    uint32_t localid = 60001;
    
    // 期望交易适配器接收撤单请求
    EXPECT_CALL(*mock_trader_, cancel(localid))
        .Times(1)
        .WillOnce(Return(true));
    
    // 执行撤单操作
    bool result = ctx_->stra_cancel(localid);
    
    // 验证撤单结果
    EXPECT_TRUE(result);
    
    std::cout << "撤单功能测试通过" << std::endl;
}

/**
 * @brief 测试持仓查询
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestPositionQuery) {
    const char* stdCode = "SHFE.rb2501";
    
    // 设置不同的持仓情况
    EXPECT_CALL(*mock_trader_, getPosition(stdCode, false))
        .WillOnce(Return(10.0))  // 多头持仓
        .WillOnce(Return(-5.0))  // 空头持仓
        .WillOnce(Return(0.0));  // 无持仓
    
    // 测试多头持仓
    double longPos = ctx_->stra_get_position(stdCode);
    EXPECT_EQ(longPos, 10.0);
    
    // 测试空头持仓
    double shortPos = ctx_->stra_get_position(stdCode);
    EXPECT_EQ(shortPos, -5.0);
    
    // 测试无持仓
    double noPos = ctx_->stra_get_position(stdCode);
    EXPECT_EQ(noPos, 0.0);
    
    std::cout << "持仓查询测试通过" << std::endl;
}

/**
 * @brief 测试数据订阅
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestDataSubscription) {
    const char* stdCode = "SHFE.rb2501";
    
    // 期望引擎接收订阅请求
    EXPECT_CALL(*mock_engine_, sub_tick(_, stdCode))
        .Times(4); // Tick、委托队列、委托明细、成交明细各一次
    
    // 测试各种数据订阅
    EXPECT_NO_THROW(ctx_->stra_sub_ticks(stdCode));
    EXPECT_NO_THROW(ctx_->stra_sub_order_queues(stdCode));
    EXPECT_NO_THROW(ctx_->stra_sub_order_details(stdCode));
    EXPECT_NO_THROW(ctx_->stra_sub_transactions(stdCode));
    
    std::cout << "数据订阅测试通过" << std::endl;
}

/**
 * @brief 测试Tick数据回调
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestTickDataCallback) {
    const char* stdCode = "SHFE.rb2501";
    
    // 模拟Tick数据回调
    EXPECT_NO_THROW(ctx_->on_tick(stdCode, test_tick_));
    
    std::cout << "Tick数据回调测试通过" << std::endl;
}

/**
 * @brief 测试交易时段回调
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestSessionCallbacks) {
    uint32_t tradingDate = 20241219;
    
    // 测试交易时段开始回调
    EXPECT_NO_THROW(ctx_->on_session_begin(tradingDate));
    
    // 测试交易时段结束回调
    EXPECT_NO_THROW(ctx_->on_session_end(tradingDate));
    
    std::cout << "交易时段回调测试通过" << std::endl;
}

/**
 * @brief 测试日志功能
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestLogging) {
    // 测试不同级别的日志输出
    EXPECT_NO_THROW(ctx_->stra_log_info("HFT策略信息日志测试"));
    EXPECT_NO_THROW(ctx_->stra_log_debug("HFT策略调试日志测试"));
    EXPECT_NO_THROW(ctx_->stra_log_error("HFT策略错误日志测试"));
    
    std::cout << "日志功能测试通过" << std::endl;
}

/**
 * @brief 测试异常处理
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestExceptionHandling) {
    // 测试空指针处理
    EXPECT_NO_THROW(ctx_->on_tick(nullptr, nullptr));
    
    // 测试无效合约代码
    double invalidPos = ctx_->stra_get_position("");
    EXPECT_EQ(invalidPos, 0.0);
    
    // 测试交易适配器断开连接
    ON_CALL(*mock_trader_, isConnected())
        .WillByDefault(Return(false));
    
    OrderIDs orders = ctx_->stra_buy("SHFE.rb2501", 4000.0, 10.0, "test");
    // 连接断开时的行为取决于具体实现
    
    std::cout << "异常处理测试通过" << std::endl;
}

/**
 * @brief 测试完整HFT工作流程
 */
TEST_F(HftStraBaseCtxComprehensiveTest, TestCompleteHFTWorkflow) {
    const char* stdCode = "SHFE.rb2501";
    double price = 4000.0;
    double qty = 10.0;
    
    // 1. 策略初始化
    EXPECT_NO_THROW(ctx_->on_init());
    
    // 2. 订阅数据
    EXPECT_NO_THROW(ctx_->stra_sub_ticks(stdCode));
    
    // 3. 交易时段开始
    EXPECT_NO_THROW(ctx_->on_session_begin(20241219));
    
    // 4. 接收Tick数据
    EXPECT_NO_THROW(ctx_->on_tick(stdCode, test_tick_));
    
    // 5. 执行高频交易
    OrderIDs buy_orders = ctx_->stra_buy(stdCode, price - 1.0, qty, "hft_buy");
    EXPECT_GT(buy_orders.size(), 0);
    
    OrderIDs sell_orders = ctx_->stra_sell(stdCode, price + 1.0, qty, "hft_sell");
    EXPECT_GT(sell_orders.size(), 0);
    
    // 6. 查询状态
    double position = ctx_->stra_get_position(stdCode);
    double fund = ctx_->stra_get_fund_data(0);
    
    EXPECT_GE(position, 0.0);
    EXPECT_GT(fund, 0.0);
    
    // 7. 撤销订单
    if (buy_orders.size() > 0) {
        bool cancel_result = ctx_->stra_cancel(buy_orders[0]);
        (void)cancel_result; // 避免未使用变量警告
    }
    
    // 8. 交易时段结束
    EXPECT_NO_THROW(ctx_->on_session_end(20241219));
    
    std::cout << "完整HFT工作流程测试通过" << std::endl;
    std::cout << "- 最终持仓: " << position << std::endl;
    std::cout << "- 资金状况: " << fund << std::endl;
    std::cout << "- 买入订单数: " << buy_orders.size() << std::endl;
    std::cout << "- 卖出订单数: " << sell_orders.size() << std::endl;
} 